package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.wemedia.WemediaConstants;
import com.heima.common.constants.NewsAutoScanConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Resource
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Resource
    WmMaterialMapper wmMaterialMapper;
    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
    WmNewsMapper wmNewsMapper;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页(起始页数据)
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if(StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVo> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }

    /**
     * 查询需要发布的文章id列表
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        //查询状态为4或为8的数据且发布时间小于当前时间实例的id
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery()
                .le(WmNews::getPublishTime,new Date())
                .in(WmNews::getStatus,4,8)
                .select(WmNews::getId)
        );

        List<Integer> idList = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return idList;
    }

    /**
     * 查询所有文章
     * @param wmNewsPageReqDto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto wmNewsPageReqDto) {
        //1.参数校验
        if (wmNewsPageReqDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmNewsPageReqDto.checkParam();
        //2.执行业务
        //模糊查询关键字
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();

        if (wmNewsPageReqDto.getKeyword()!=null){
            wrapper.like(WmNews::getTitle,wmNewsPageReqDto.getKeyword());
        }

        //状态
        if (wmNewsPageReqDto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, wmNewsPageReqDto.getStatus());
        }
        //开始时间，结束时间
        if (wmNewsPageReqDto.getBeginPubDate() != null && wmNewsPageReqDto.getEndPubDate() != null) {
            wrapper.between(WmNews::getPublishTime, wmNewsPageReqDto.getBeginPubDate(), wmNewsPageReqDto.getBeginPubDate());
        }
        //频道ID
        if (wmNewsPageReqDto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, wmNewsPageReqDto.getChannelId());
        }

        //对应当前自媒体人
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        //时间排序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //分页
        Page<WmNews> page = new Page<>(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize());

        //3 执行查询
        IPage<WmNews> pageResult = page(page, wrapper);
        //3.返回结果
        ResponseResult result = new PageResponseResult
                (wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize(), pageResult.getTotal(), pageResult.getRecords());
        // 处理文章图片
        result.setHost(webSite);
        return result;
    }

    /**
     * 发布文章
     * @param dto
     * @param isSubmit  是否为提交 1 为提交 0为草稿
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //1. 参数校验
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2. 保存或修改文章
        WmNews wmNews = new WmNews();
        //   封装设置参数
        BeanUtils.copyProperties(dto,wmNews);
        //   封面类型
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        String images = imageListToStr(dto.getImages(), webSite);
        if (StringUtils.isNotBlank(images)) {
            wmNews.setImages(images);
        }
        saveWmNews(wmNews);


        //3. 关联文章和素材关系表
        // 解析文章内容中的图片列表
        List<Map> contentList = JSON.parseArray(dto.getContent(), Map.class);
        List<String> materials = parseContentImages(contentList);

        //   * 关联**内容**中的图片与素材的关系
        if (isSubmit == WmNews.Status.SUBMIT.getCode() && materials.size() > 0) {
            saveRelativeInfoForContent(materials, wmNews.getId());
        }
        //   * 关联**封面**中的图片与素材的关系
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            saveRelativeInfoForCover(dto, materials,wmNews);
        }

        // 4 发消息给admin审核文章
        Map map = new HashMap();
        map.put("wmNewsId", wmNews.getId());
        kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(map));

        //4. 封装返回成功结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存文章 封面 和素材关系
     * @param dto 前端参数   # images 图片封面带前缀
     * @param materials 文章内容中的图片列表#无图片前缀
     * @param wmNews 文章对象
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, List<String> materials, WmNews wmNews) {
        //1 获取dto 图片封面
        List<String> images = dto.getImages();

        //2 判断type是否为自动
        //     > 封面图片如果选择是自动需要从内容中截图图片做为封面图片
        //     > 截取规则为：
        //     > * 内容图片的个数小于等于2  则为单图截图一张图
        //     > * 内容图片大于2，则为多图，截图三张图
        //     > * 内容中没有图片，则为无图
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {

            int size = materials.size();
            if (size > 0 && size <= 2) { // 单图
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);

            } else if (size > 2) { // 多图
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else { // 无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            if (images != null) {
                wmNews.setImages(imageListToStr(images, webSite));
            }
            updateById(wmNews);
        }

        //3 执行保存文章封面和素材关系
        if (images != null && images.size() > 0) {
            saveRelativeInfoForImage(images, wmNews.getId());
        }

    }

    /**
     * 保存文章封面和图片关系
     * @param images
     * @param wmNewsId
     */
    private void saveRelativeInfoForImage(List<String> images, Integer wmNewsId) {
        images = images.stream().map( x ->
                x.replace(webSite,"").replace(" ","") )
                .collect(Collectors.toList());

        saveRelativeInfo(images, wmNewsId, WemediaConstants.WM_IMAGE_REFERENCE);
    }

    /**
     * 保存文章 内容和素材关系
     * @param materials  内容图片列表
     * @param wmNewsId 文章id
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer wmNewsId) {
        saveRelativeInfo(materials, wmNewsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 执行保存文章素材关系
     * @param materials 素材URL列表
     * @param wmNewsId 文章id
     * @param type 引用类型  0：内容  1：封面
     */
    private void saveRelativeInfo(List<String> materials, Integer wmNewsId, Short type) {
        // 1 根据url 查询素材对应的id
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, materials)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));

        if (dbMaterials == null || dbMaterials.size() == 0) {
            throw new CustomException(AppHttpCodeEnum.FILE_MATERIAL_ISNULL_ERROR);
        }
        // 2 判断文章素材是否存在
        // dbMaterials(少) 1 2 3  materials（多） 1 2 3 4
        // {"1.jpg":1, "2.jpg":2 ....}
//        HashMap map = new HashMap();
//        for (WmMaterial dbMaterial : dbMaterials) {
//            map.put(dbMaterial.getUrl(), dbMaterial.getId());
//        }
        Map<String, Integer> matreialMap = dbMaterials.stream()
                .collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));

        // 存放素材对应的id
        List<Integer> materialIds = new ArrayList<>();

        for (String url : materials) {
            Integer id = matreialMap.get(url);
            // 数据库的素材被删除
            if (id == null) {
                CustException.cust(AppHttpCodeEnum.FILE_MATERIAL_ISNULL_ERROR);
            }

            materialIds.add(id);
        }


        //3 执行保存(批量保存)
        wmNewsMaterialMapper.saveRelations(materialIds, wmNewsId, type);
    }


    /**
     * 抽取文章内容中的图片url列表
     * @param contentList 内容列表
     * @return
     */
    private List<String> parseContentImages(List<Map> contentList) {
        List<String> materials = new ArrayList<>();

        for (Map<String, String> content : contentList) {
            if (content.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)) {
                String imageUrl = content.get("value")
                        .replace(webSite,"")
                        .replace(" ","");

                materials.add(imageUrl);
            }
        }

        return materials;
    }

    /**
     * 保存或修改文章
     * @param wmNews
     */
    private void saveWmNews(WmNews wmNews) {
        //   * 该功能为保存、修改（是否有id）、保存草稿的共用方法
        //   * 如果有id修改文章，先删除所有素材关联关系
        //   * 如果没有id，保存文章

        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UPENABLE); // 上架

        if (wmNews.getId() == null) {// 新增
            save(wmNews);
        } else { // 修改
            // 删除文章和素材关系
            wmNewsMaterialMapper.delete(
                    Wrappers.<WmNewsMaterial>lambdaQuery()
                            .eq(WmNewsMaterial::getNewsId, wmNews.getId()
                            )
            );

            updateById(wmNews);
        }
    }

    /**
     * 抽取前端文章封面列表装换成字符串
     * material/2021/1/20210104/1.jpg,material/2021/1/20210104/2.jpg,material/2021/1/20210104/3.jpg
     * @param images
     * @param webSite
     * @return
     */
    private String imageListToStr(List<String> images, String webSite) {
        if (images.size() > 0) {

            return images.toString()
                    .replace("[","")
                    .replace("]","")
                    .replace(webSite,"")
                    .replace(" ","");
        }
        return null;
    }

    /**
     * 查询文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.执行逻辑
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 处理封面图片的前缀
        String images = wmNews.getImages();
        StringBuffer sb = new StringBuffer();
        if (StringUtils.isNotBlank(images)) {
            String[] split = images.split(",");
            for (String image : split) {
                image = webSite + image;
                sb.append(images).append(",");
            }
            images = sb.toString().substring(0,sb.toString().lastIndexOf(","));
            wmNews.setImages(images);
        }
        //3.返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);

        return result;
    }

    /**
     * 删除文章
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //1.校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 2.判断状态 上架且发布则无法删除
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED)
                && wmNews.getEnable().equals( WemediaConstants.WM_NEWS_UPENABLE)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }

        // 删除文章
        removeById(id);

        //3.删除文章和素材的关系
        wmNewsMaterialMapper.delete(
                Wrappers.<WmNewsMaterial>lambdaQuery()
                        .eq(WmNewsMaterial::getNewsId, wmNews.getId()
                        )
        );

        //4，返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 上架或下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }

        //4.修改文章状态，同步到app端（后期做）
        wmNews.setEnable(dto.getEnable());
        updateById(wmNews);

        // 同步到APP端文章配置信息 id，enable 0下架  1上架
        if (wmNews.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", dto.getEnable());

            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,
                    JSON.toJSONString(map));
        }


        //5 返回结果

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
